package com.jiyun.leyou.intercept;

import com.jiyun.leyou.pojo.UserInfo;
import com.jiyun.leyou.properties.JwtProperties;
import com.jiyun.leyou.util.JwtUtils;
import com.leyou.common.util.CookieUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserIntercept extends HandlerInterceptorAdapter {

    @Autowired
    JwtProperties jwtProperties;

    private static final ThreadLocal<UserInfo> THREAD_LOCAL = new ThreadLocal<>();

    // 每一个请求，都是一个独立的线程
    // 并发量：同一时间内，可以处理的请求数量

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在拦截器中获取token
        String token = CookieUtils.getCookieValue(request, "LY_TOKEN");
        if(token==null){
            // 设置状态码为401
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }

        UserInfo userInfo = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
        System.out.println(userInfo);

        // 将数据存放在ThreadLocal中
        // ThreadLocal是属于谁的？属于某一个线程
        // ThreadLocal生命周期是什么？我们给他new出来，他就生，线程死他才死
        // 线程会不会死？tomcat，线程池！
        // 线程池：会将很多线程对象，存放在一起，用的时候调用，用完之后返还
        THREAD_LOCAL.set(userInfo);


        return true;
    }

    // 再线程用完的时候，清空ThreadLocal即可
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        THREAD_LOCAL.remove();
    }

    public static UserInfo getUserInfo(){
        return THREAD_LOCAL.get();
    }

}
